package com.mk.plugin.generator;

import com.intellij.ide.fileTemplates.FileTemplate;
import com.intellij.ide.fileTemplates.FileTemplateManager;
import com.intellij.ide.fileTemplates.FileTemplateUtil;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiDirectory;
import com.mk.plugin.function.Functions;

import java.util.*;

public class IndexGenerator {

    public void generator(Project project, Properties p, PsiDirectory dir, List<Functions> functionsList) {
        FileTemplate indexTemplate = FileTemplateManager.getInstance(project).getInternalTemplate("index");
        Map<String, Object> properties = new HashMap<>(); // 拷贝新的properties
        for (Object o : p.keySet()) {
            properties.put((String) o, p.get(o));
        }

        boolean needToolbar = false;
        boolean needToolbarLeft = false;
        boolean needPagination = false;
        Set<String> toolbarLeftActionList = new HashSet<>();
        Set<String> subviewProps = new HashSet<>();
        Set<String> mapToProps = new HashSet<>();
        Set<String> subviewStatements = new HashSet<>();
        Set<String> MKComponentImport = new HashSet<>();
        Set<String> customImportStatement = new HashSet<>();

        for (Functions f : functionsList) {
            if (f.getNeedComponent().contains("MKToolbar")) {
                needToolbar = true;
            }

            if (f.getNeedComponent().contains("MKToolbarLeftAction")) {
                needToolbarLeft = true;
                toolbarLeftActionList.add(f.getLeftActionComponentString());
                subviewProps.addAll(f.getSubviewProps());
            }

            if (f.getNeedComponent().contains("Pagination")) {
                needPagination = true;
            }

            mapToProps.addAll(f.getNeedMapToProps());
            subviewStatements.add(f.getSubviewStatement());
            MKComponentImport.addAll(f.getMKComponentImport());
            customImportStatement.addAll(f.getCustomImportStatement());
        }

        properties.put("needToolbar", needToolbar);
        properties.put("needToolbarLeft", needToolbarLeft);
        properties.put("needPagination", needPagination);
        properties.put("leftActionString", toolbarLeftActionList);
        properties.put("subviewProps", subviewProps);
        properties.put("mapToProps", mapToProps);
        properties.put("subviewStatements", subviewStatements);
        properties.put("MKComponentImport", MKComponentImport);
        properties.put("customImportStatement", customImportStatement);

        try {
            FileTemplateUtil.createFromTemplate(indexTemplate, properties.get("underscore_name") + ".index.tsx", properties, dir, getClass().getClassLoader());

        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }
}
